from sanic.views import HTTPMethodView
from sanic.response import json
from processing.other_func import ProToken,Sercret_all,Serialization,Random_id,date_format
import json as jn
from processing.Sql_DataFrom import ProJosn
from processing.comm import sqlPaging,sqlOrder,set_status,timestamp_to_standard

# 功能列表
class functionList(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.args.get('user_id','') or request.app.ctx.user_id
        client_ip = request.ip
        pageNum = int(request.args.get('pageNum', 1))
        pageSize = int(request.args.get('pageSize', 10))
        keyword = request.args.get('keyword', '')
        try:

            sql = f"""
                select plugin_id,id,title,name,icon,auths,frameSrc,menuType,showLink,menuRank from authority_menus where user_id='{user_id}'
                and menuType=3 or menuType=4
            """
            tol = f""" SELECT COUNT(*) FROM authority_menus where  user_id='{user_id}' and menuType=3 or menuType=4  """
            sql = sqlOrder(sql, 'menuRank', 'ASC')
            sql = sqlPaging(pageNum, pageSize, sql)

            sql_data = db.find_all(sql)
            tol_data = db.find_one(tol)
            if sql_data:

                data = ProJosn(sql_data,sql)
            else:
                data = []
            return json({'code': 200, 'message': "请求成功!", 'data': {
                'list':data,
                'total':tol_data[0]
            }})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/functionList', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)
class functionAdd(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.args.get('user_id', '') or request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        try:

            # 查询同步的插件是否已同步
            sql_plugin = f"""
                select plugin_id from authority_menus where plugin_id='{html_data['plugin_id']}'
            """

            plugin_find = db.find_one(sql_plugin)
            if plugin_find:
                return json({'code': 201, 'message': "已同步该插件!"})

            sql = f"""
                insert into authority_menus(user_id,plugin_id,title,name,menuType,icon,auths,showLink,frameSrc,menuRank,
                       status,ctime ) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,now())
            """

            db.insert(sql,(
                user_id,
                html_data['plugin_id'],
                html_data['title'],
                html_data['name'],
                int(html_data['menuType']),
                html_data['icon'],
                html_data['auths'],
                int(html_data['showLink']),
                html_data['frameSrc'],
                int(html_data['menuRank']),
                'normal',
                ))

            return json({'code': 200, 'message': "添加成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/functionAdd', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)
class functionEdit(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.args.get('user_id', '') or request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        try:
            sql = """
                update authority_menus set title=%s,name=%s,menuType=%s,icon=%s,auths=%s,showLink=%s,frameSrc=%s,menuRank=%s where id=%s
            """

            db.update(sql,(
                html_data['title'],
                html_data['name'],
                int(html_data['menuType']),
                html_data['icon'],
                html_data['auths'],
                int(html_data['showLink']),
                html_data['frameSrc'],
                int(html_data['menuRank']),
                int(html_data['id'])
            ))

            return json({'code': 200, 'message': "修改成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/functionEdit', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)
class functionDelete(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json

        try:
            sql = "delete from authority_menus where id=%s"
            db.delete(sql, (html_data['id']))
            return json({'code': 200, 'message': "删除成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/functionDelete', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

#  讲插件同步到功能列表(好增删改查)
